﻿using CSuperSocket.Facility.Protocol;
using CSuperSocket.SocketBase.Protocol;
using System;
using System.Collections.Generic;
using System.Text;
using WebSvrUpdaterCore.Models;
using Newtonsoft.Json;
using NLog;
namespace WebUpdaterAdminCore
{
    public class DefaultBeginEndMarkReceiveFilter : BeginEndMarkReceiveFilter<MsgPacket>
    {
        private static Logger _logger = LogManager.GetCurrentClassLogger();
        private readonly static byte[] BeginMark = new byte[] { (byte)'!' };
        private readonly static byte[] EndMark = new byte[] { (byte)'$' };
        public DefaultBeginEndMarkReceiveFilter()
            : base(BeginMark, EndMark)
        {

        }
        protected override MsgPacket ProcessMatchedRequest(byte[] readBuffer, int offset, int length)
        {
            MsgPacket msgPacket = null;
            string jsonStr = "";
            try
            {
                var startIdx = offset + BeginMark.Length;
                var len = length - BeginMark.Length - EndMark.Length;
                jsonStr = Encoding.UTF8.GetString(readBuffer, startIdx, len);//.TrimStart((char)BeginMark[0]).TrimEnd((char)EndMark[0]);

                msgPacket = JsonConvert.DeserializeObject<MsgPacket>(jsonStr);
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "【ProcessMatchedRequest】解析数据失败,json:{0}",jsonStr);
                Console.WriteLine("【ProcessMatchedRequest】解析数据失败, json:{ 0}", jsonStr);
            }
                return msgPacket;

        }
    }
}
